package com.will.txj.wy.files.config;

import com.jcraft.jsch.ChannelSftp;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: wen-yi;
 * @date: 2021/12/4 14:25;
 * @Description:
 */
@Component
public class SftpPool {
    private SftpClientFactory factory;
    private final GenericObjectPool<ChannelSftp> internalPool;

    //初始化连接池
    public SftpPool(@Autowired SftpClientFactory factory) {
        this.factory = factory;
        SftpConfig config = factory.getConfig();
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(config.getMaxTotal());
        poolConfig.setMinIdle(config.getMinIdel());
        poolConfig.setMaxIdle(config.getMaxIdle());
        poolConfig.setMaxWaitMillis(config.getMaxWaitMillis());
        this.internalPool = new GenericObjectPool<ChannelSftp>(factory, poolConfig);
    }

    //从连接池中取连接
    public ChannelSftp getChannelSftp() throws Exception {
        return internalPool.borrowObject();
    }

    //将链接归还到连接池
    public void returnChannelSftp(ChannelSftp ftpClient) {
        internalPool.returnObject(ftpClient);
    }

    /**
     * 销毁池子
     */
    public void destroy() {
        try {
            internalPool.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
